#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
微信公众号草稿管理工具
支持新增草稿、获取草稿列表、更新草稿、删除草稿等功能
"""

import requests
import json
import os
from typing import Optional, Dict, Any, List
from wechat_token import WeChatTokenManager

class WeChatDraftManager:
    """
    微信公众号草稿管理类
    """
    
    def __init__(self, token_manager: WeChatTokenManager):
        """
        初始化
        :param token_manager: Token管理器实例
        """
        self.token_manager = token_manager
        self.base_url = "https://api.weixin.qq.com/cgi-bin/draft"
    
    def add_draft(self, articles: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        新增草稿
        :param articles: 图文素材集合
        :return: 添加结果
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/add"
        params = {'access_token': access_token}
        
        data = {'articles': articles}
        
        try:
            print("正在新增草稿...")
            
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"新增草稿失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            print(f"✅ 草稿新增成功!")
            print(f"Media ID: {result.get('media_id')}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def create_news_article(self, 
                          title: str,
                          content: str,
                          thumb_media_id: str,
                          author: str = "",
                          digest: str = "",
                          content_source_url: str = "",
                          need_open_comment: int = 0,
                          only_fans_can_comment: int = 0) -> Dict[str, Any]:
        """
        创建图文消息文章结构
        :param title: 标题
        :param content: 内容（HTML格式）
        :param thumb_media_id: 缩略图媒体ID
        :param author: 作者
        :param digest: 摘要
        :param content_source_url: 原文链接
        :param need_open_comment: 是否开启评论（0-不开启，1-开启）
        :param only_fans_can_comment: 是否仅粉丝可评论（0-所有人，1-仅粉丝）
        :return: 文章结构
        """
        return {
            "article_type": "news",
            "title": title,
            "author": author,
            "digest": digest,
            "content": content,
            "content_source_url": content_source_url,
            "thumb_media_id": thumb_media_id,
            "need_open_comment": need_open_comment,
            "only_fans_can_comment": only_fans_can_comment
        }
    
    def create_image_article(self,
                           title: str,
                           content: str,
                           image_media_ids: List[str],
                           need_open_comment: int = 0,
                           only_fans_can_comment: int = 0,
                           cover_crop_info: Optional[List[Dict]] = None) -> Dict[str, Any]:
        """
        创建图片消息文章结构
        :param title: 标题
        :param content: 内容
        :param image_media_ids: 图片媒体ID列表
        :param need_open_comment: 是否开启评论
        :param only_fans_can_comment: 是否仅粉丝可评论
        :param cover_crop_info: 封面裁剪信息
        :return: 图片文章结构
        """
        image_list = [{"image_media_id": media_id} for media_id in image_media_ids]
        
        article = {
            "article_type": "newspic",
            "title": title,
            "content": content,
            "need_open_comment": need_open_comment,
            "only_fans_can_comment": only_fans_can_comment,
            "image_info": {
                "image_list": image_list
            }
        }
        
        if cover_crop_info:
            article["cover_info"] = {
                "crop_percent_list": cover_crop_info
            }
        
        return article
    
    def get_draft_list(self, offset: int = 0, count: int = 20, no_content: int = 0) -> Dict[str, Any]:
        """
        获取草稿列表
        :param offset: 从全部草稿中的该偏移位置开始返回
        :param count: 返回草稿的数量，取值在1到20之间
        :param no_content: 1表示不返回content字段，0表示返回
        :return: 草稿列表
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/batchget"
        params = {'access_token': access_token}
        
        data = {
            'offset': offset,
            'count': count,
            'no_content': no_content
        }
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"获取草稿列表失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def get_draft_count(self) -> Dict[str, Any]:
        """
        获取草稿总数
        :return: 草稿总数
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/count"
        params = {'access_token': access_token}
        
        try:
            response = requests.get(url, params=params, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"获取草稿总数失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def update_draft(self, media_id: str, index: int, articles: List[Dict[str, Any]]) -> bool:
        """
        更新草稿
        :param media_id: 草稿的media_id
        :param index: 要更新的文章在图文消息中的位置（多图文消息时，此字段才有意义），第一篇为0
        :param articles: 图文素材集合
        :return: 更新是否成功
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/update"
        params = {'access_token': access_token}
        
        data = {
            'media_id': media_id,
            'index': index,
            'articles': articles
        }
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"更新草稿失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            print(f"✅ 草稿更新成功: {media_id}")
            return True
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def delete_draft(self, media_id: str) -> bool:
        """
        删除草稿
        :param media_id: 草稿的media_id
        :return: 删除是否成功
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/delete"
        params = {'access_token': access_token}
        
        data = {'media_id': media_id}
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"删除草稿失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            print(f"✅ 草稿删除成功: {media_id}")
            return True
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")
    
    def get_draft_detail(self, media_id: str) -> Dict[str, Any]:
        """
        获取草稿详情
        :param media_id: 草稿的media_id
        :return: 草稿详情
        """
        access_token = self.token_manager.get_access_token()
        
        url = f"{self.base_url}/get"
        params = {'access_token': access_token}
        
        data = {'media_id': media_id}
        
        try:
            response = requests.post(url, params=params, json=data, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                raise Exception(f"获取草稿详情失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            
            return result
            
        except requests.RequestException as e:
            raise Exception(f"网络请求失败: {e}")
        except json.JSONDecodeError as e:
            raise Exception(f"解析响应失败: {e}")


def create_draft_with_tepian():
    """使用tepian.png素材创建草稿"""
    from config import WECHAT_CONFIG
    
    print("=== 使用tepian.png素材创建草稿 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("❌ 请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    # 读取上传结果
    result_file = 'tepian_upload_result.json'
    if not os.path.exists(result_file):
        print(f"❌ 找不到素材上传结果文件: {result_file}")
        print("请先运行: python upload_material_example.py tepian")
        return
    
    try:
        with open(result_file, 'r', encoding='utf-8') as f:
            upload_result = json.load(f)
        
        thumb_media_id = upload_result.get('media_id')
        if not thumb_media_id:
            print("❌ 无法获取素材ID")
            return
        
        print(f"📋 使用素材ID: {thumb_media_id}")
        
        # 创建token管理器和草稿管理器
        token_manager = WeChatTokenManager(
            WECHAT_CONFIG['APP_ID'], 
            WECHAT_CONFIG['APP_SECRET']
        )
        draft_manager = WeChatDraftManager(token_manager)
        
        # 创建图文消息文章
        article = draft_manager.create_news_article(
            title="欢迎关注我们的公众号！",
            content="""
            <p>感谢您关注我们的微信公众号！</p>
            <p>我们将为您提供最新的资讯和优质的内容。</p>
            <p>如果您有任何问题或建议，欢迎随时与我们联系。</p>
            <p><strong>让我们一起成长，一起进步！</strong></p>
            """,
            thumb_media_id=thumb_media_id,
            author="公众号团队",
            digest="欢迎关注我们，获取最新资讯和优质内容",
            need_open_comment=1,
            only_fans_can_comment=0
        )
        
        # 新增草稿
        result = draft_manager.add_draft([article])
        
        print(f"✅ 草稿创建成功!")
        print(f"草稿Media ID: {result.get('media_id')}")
        
        # 保存草稿结果
        with open('tepian_draft_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 草稿结果已保存到: tepian_draft_result.json")
        
        return result
        
    except Exception as e:
        print(f"❌ 创建草稿失败: {e}")


def example():
    """
    使用示例
    """
    from config import WECHAT_CONFIG
    
    print("=== 微信公众号草稿管理示例 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("⚠️  请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    # 创建token管理器和草稿管理器
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    draft_manager = WeChatDraftManager(token_manager)
    
    try:
        print("\n1. 获取草稿总数...")
        count_info = draft_manager.get_draft_count()
        print(f"草稿总数: {count_info.get('total_count', 0)}")
        
        print("\n2. 获取草稿列表...")
        draft_list = draft_manager.get_draft_list(0, 5, 1)  # 不返回content字段
        print(f"草稿列表数量: {len(draft_list.get('item', []))}")
        
        for i, item in enumerate(draft_list.get('item', [])):
            print(f"  草稿 {i+1}:")
            print(f"    Media ID: {item.get('media_id')}")
            print(f"    更新时间: {item.get('update_time')}")
            if item.get('content') and item['content'].get('news_item'):
                news_item = item['content']['news_item'][0]
                print(f"    标题: {news_item.get('title', '无标题')}")
                print(f"    作者: {news_item.get('author', '无作者')}")
        
        print("\n✅ 示例运行完成！")
        
    except Exception as e:
        print(f"❌ 运行失败: {e}")


if __name__ == '__main__':
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == 'tepian':
        create_draft_with_tepian()
    else:
        example()
